<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\jia;

use app\api\service\User as UserService;
use app\common\library\junziqian\Driver as DriverModel;
use app\common\model\jia\Contract as ContractModel;
use app\common\service\Order as OrderService;
use think\facade\Db;

/**
 * 商家门店模型
 * Class Shop
 * @package app\store\model\store
 */
class Contract extends ContractModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'is_delete',
        'store_id',
        'create_time',
        'update_time',
    ];

    public function add(int $orderId, $data = [])
    {

        $data['is_delete'] = 0;

        $data['order_id'] = $orderId;
        $data['store_id'] = self::$storeId;

        $this->save($data);

        // 地址
        return $data;
    }

    //签约
    public function updateFace(array $data)
    {
        $this->save([
            'face_status' => $data['faceStatus'],

        ]);
        if ($data['faceStatus'] == 1) {

            //$chapteJson[0]               = ['page' => 0, 'chaptes' => [['offsetX' => 0.3047, 'offsetY' => 0.2677]]];
            //$chapteJson[0]               = ['page' => 0, 'chaptes' => [['offsetX' => 0.3047, 'offsetY' => 0.2677]]];
            $signatories['fullName']     = $this['face_name'];
            $signatories['identityCard'] = $this['face_idcard'];
            $signatories['mobile']       = $this['face_mobile'];
            $signatories['identityType'] = 1;
            $signatories['signLevel']    = 3;
            $signatories['serverCaAuto'] = 0;
            $signatories['searchKey']    = '甲方签字';

            $signatoriesCompany['fullName']     = '广西佳佳陪护理机构服务有限公司';
            $signatoriesCompany['identityCard'] = '91450902MAC8CTCD34';
            $signatoriesCompany['email']        = '3663880372@qq.com';
            $signatoriesCompany['identityType'] = 12;
            $signatoriesCompany['signLevel']    = 0;
            $signatoriesCompany['serverCaAuto'] = 1;
            $signatoriesCompany['searchKey']    = '盖章';

            //$signatories['chapteJson']   = json_encode($chapteJson);

            $templateParams['manageName']   = $this['order']['manage']['real_name'];
            $templateParams['manageMobile'] = $this['order']['manage']['mobile'];
            $templateParams['faceName']     = $data['face_name'];
            $templateParams['faceMobile']   = $data['face_mobile'];
            $templateParams['faceMobile1']  = $data['face_mobile'];
            $templateParams['realName']     = $this['real_name'];
            $templateParams['sex']          = $this['order']['sex'];
            $templateParams['age']          = $data['age'];
            $templateParams['idcard']       = $data['idcard'];
            $templateParams['build']        = $this['order']['build']['name'];
            $templateParams['floor']        = $this['order']['floor'];
            $templateParams['bedNo']        = $this['order']['bed_no'];
            $templateParams['room']         = $this['order']['room'];

            $start = explode('-', $this['order']['start_date']);

            $templateParams['startYear']  = $start[0];
            $templateParams['startMonth'] = $start[1];
            $templateParams['startDay']   = $start[2];

            $end = explode('-', $this['order']['end_date']);

            $templateParams['endYear']  = $end[0];
            $templateParams['endMonth'] = $end[1];
            $templateParams['endDay']   = $end[2];

            $peihu_time = explode('-', $this['order']['peihu_time']);

            $templateParams['startTime'] = $peihu_time[0];
            $templateParams['endTime']   = $peihu_time[1];

            $templateParams['day'] = $this['order']['day'];

            $templateParams['hour']     = 0;
            $templateParams['hourType'] = $this['order']['hour_type'] == 10 ? 12 : 24;
            $templateParams['dayFee']   = $this['order']['order_price'] / $this['order']['day']; //收费标准

            $templateParams['serviceType'] = ['一对一陪护服务'];

            $date = Date('Y-m-d');

            $date = explode('-', $date);

            $templateParams['signYear']  = $date[0];
            $templateParams['signMonth'] = $date[1];
            $templateParams['signDay']   = $date[2];

            $goods_id = Db::name('order_goods')
                ->where('order_id', $this['order_id'])->value('goods_id');
            $contract_type = Db::name('goods')
                ->where('goods_id', $goods_id)->value('contract_type');
            $templateNo = Db::name('contract_type')->where('category_id', $contract_type)->value('template_id');

            $model = new DriverModel;
            // $data['orderNo']        = OrderService::createOrderNo();
            $data['contractName']   = '佳佳陪护协议';
            $data['signatories']    = json_encode([$signatories, $signatoriesCompany]);
            $data['serverCa']       = 1;
            $data['positionType']   = 2;
            $data['dealType']       = 0; //手签
            $data['fileType']       = 4; //pdf模版
            $data['templateNo']     = $templateNo;
            $data['templateParams'] = json_encode($templateParams);

            // $data['url'] = base_url() . $this['path'];

            $result = $model->applySign($data);
            //print_r($result);exit;
            if (isset($result['data'])) {
                $this->save([
                    'contract_no' => $result['data'],

                ]);
            }

            return $result;

        }

        // 更新
        return $data;
    }

    public function saveUrlToFile($url, $filePath)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $data = curl_exec($ch);
        curl_close($ch);

        $success = file_put_contents($filePath, $data);
        return $success ? true : false;
    }
    public function edit(array $data): bool
    {

        // 更新收货地址
        return $this->save([
            'real_name' => $data['real_name'],
            'mobile'    => $data['mobile'],
            'sex'       => $data['sex'],
            'idcard'    => $data['idcard'],
            'age'       => $data['age'],

        ]) !== false;
    }

    public function getFaceResult($data): bool
    {

        $is_face = $data['code'] == "0" ? 1 : 2;

        $this->save(['code' => $data['code'], 'is_face' => $is_face]);
        if ($data['code'] == "0") {
            return true;
        } else {
            $this->error = $data['msg'];
            return false;
        }

    }
    //发起签约-手动签-公司
    public function editCompany(array $data)
    {

        $model = new DriverModel;

        $signatoriesCompany['fullName']     = '广西佳佳陪护理机构服务有限公司';
        $signatoriesCompany['identityCard'] = '91450902MAC8CTCD34';
        $signatoriesCompany['email']        = '3663880372@qq.com';
        $signatoriesCompany['identityType'] = 12;
        $signatoriesCompany['signLevel']    = 0;
        $signatoriesCompany['serverCaAuto'] = 1;
        $signatoriesCompany['orderNum']     = 1;
        $signatoriesCompany['searchKey']    = '盖章';

        //$signatories['chapteJson']   = json_encode($chapteJson);

        $templateParams['manageName']   = $this['order']['manage']['real_name'];
        $templateParams['manageMobile'] = $this['order']['manage']['mobile'];

        $templateParams['build'] = $this['order']['build']['name'];
        $templateParams['floor'] = $this['order']['floor'];
        $templateParams['bedNo'] = $this['order']['bed_no'];
        $templateParams['room']  = $this['order']['room'];

        $start = explode('-', $this['order']['start_date']);

        $templateParams['startYear']  = $start[0];
        $templateParams['startMonth'] = $start[1];
        $templateParams['startDay']   = $start[2];

        $end = explode('-', $this['order']['end_date']);

        $templateParams['endYear']  = $end[0];
        $templateParams['endMonth'] = $end[1];
        $templateParams['endDay']   = $end[2];

        $peihu_time = explode('-', $this['order']['peihu_time']);

        $templateParams['startTime'] = $peihu_time[0];
        $templateParams['endTime']   = $peihu_time[1];

        $templateParams['day'] = $this['order']['day'];

        $templateParams['hour']     = 0;
        $templateParams['hourType'] = $this['order']['hour_type'] == 10 ? 12 : 24;
        $templateParams['dayFee']   = $this['order']['goods'][0]['goods_price']; //收费标准

        $templateParams['serviceType'] = ['一对一陪护服务'];

        $date = Date('Y-m-d');

        $date = explode('-', $date);

        $templateParams['signYear']  = $date[0];
        $templateParams['signMonth'] = $date[1];
        $templateParams['signDay']   = $date[2];

        $goods_id = Db::name('order_goods')
            ->where('order_id', $this['order_id'])->value('goods_id');
        $contract_type = Db::name('goods')
            ->where('goods_id', $goods_id)->value('contract_type');
        $templateNo = Db::name('contract_type')->where('category_id', $contract_type)->value('template_id');

        $model                  = new DriverModel;
        $data['orderNo']        = OrderService::createOrderNo();
        $data['idcard']         = $data['face_idcard'];
        $data['contractName']   = '佳佳陪护协议';
        $data['signatories']    = json_encode([$signatoriesCompany]);
        $data['orderFlag']      = 1;
        $data['serverCa']       = 1;
        $data['positionType']   = 2;
        $data['dealType']       = 5; //自动签
        $data['fileType']       = 4; //pdf模版
        $data['templateNo']     = $templateNo;
        $data['templateParams'] = json_encode($templateParams);

        // $data['url'] = base_url() . $this['path'];

        if ($this['face_status'] == 0) {
            $result = $model->applySign($data);

        }

        $this->save([
            'age'         => $data['age'],
            'face_name'   => $data['face_name'],
            'face_mobile' => $data['face_mobile'],
            'idcard_date' => $data['idcard_date'],
            'idcard1'     => $data['idcard1'],
            'idcard2'     => $data['idcard2'],
            'order_no'    => $data['orderNo'],
            'contract_no' => $contract_no,
            'face_url'    => $contract_url, //签约地址
            'face_status' => 1,
            'face_idcard' => $data['face_idcard'],

        ]);

        return $rr;
    }
    //发起签约-手动签
    public function editUser(array $data)
    {

        $userId   = UserService::getCurrentLoginUserId();
        $userInfo = UserService::getCurrentLoginUser();

        if ($data['face_idcard'] != $userInfo['face_idcard']) {
            //更新个人证书
            $model              = new DriverModel;
            $dd['fullName']     = $data['face_name'];
            $dd['identityCard'] = $data['face_idcard'];
            $dd['idenFront']    = $data['idcard1_url'];
            $dd['idenReverse']  = $data['idcard2_url'];

            $ddResult = $model->cloudCertiPerInfo($dd);
            // print_r($ddResult);exit;
        }

        $userData['face_name']   = $data['face_name'];
        $userData['face_mobile'] = $data['face_mobile'];
        $userData['face_idcard'] = $data['face_idcard'];
        $userData['idcard_date'] = $data['idcard_date'];
        $userData['idcard1']     = $data['idcard1'];
        $userData['idcard2']     = $data['idcard2'];

        Db::name('user')->where('user_id', $userId)->update($userData);

        $model = new DriverModel;

        //$chapteJson[0]               = ['page' => 0, 'chaptes' => [['offsetX' => 0.3047, 'offsetY' => 0.2677]]];
        //$chapteJson[0]               = ['page' => 0, 'chaptes' => [['offsetX' => 0.3047, 'offsetY' => 0.2677]]];
        $signatories['fullName']     = $data['face_name'];
        $signatories['identityCard'] = $data['face_idcard'];
        $signatories['idcard']       = $data['face_idcard'];
        $signatories['mobile']       = $data['face_mobile'];
        $signatories['identityType'] = 1;
        $signatories['signLevel']    = 3;
        $signatories['serverCaAuto'] = 0;
        // $signatories['orderNum'] = 2;
        $signatories['searchKey'] = '甲方签字';

        $signatoriesCompany['fullName']     = '广西佳佳陪护理机构服务有限公司';
        $signatoriesCompany['identityCard'] = '91450902MAC8CTCD34';
        $signatoriesCompany['email']        = '3663880372@qq.com';
        $signatoriesCompany['identityType'] = 12;
        $signatoriesCompany['signLevel']    = 0;
        $signatoriesCompany['serverCaAuto'] = 1;
        //$signatoriesCompany['orderNum'] = 1;
        $signatoriesCompany['searchKey'] = '盖章';

        //$signatories['chapteJson']   = json_encode($chapteJson);

        $templateParams['manageName']   = $this['order']['manage']['real_name'];
        $templateParams['manageMobile'] = $this['order']['manage']['mobile'];
        $templateParams['faceName']     = $data['face_name'];
        $templateParams['faceMobile']   = $data['face_mobile'];
        $templateParams['faceMobile1']  = $data['face_mobile'];
        $templateParams['realName']     = $this['real_name'];
        $templateParams['sex']          = $this['order']['sex'];
        $templateParams['age']          = $data['age'];
        $templateParams['idcard']       = $data['face_idcard'];
        $templateParams['build']        = $this['order']['build']['name'];
        $templateParams['floor']        = $this['order']['floor'];
        $templateParams['bedNo']        = $this['order']['bed_no'];
        $templateParams['room']         = $this['order']['room'];

        $start = explode('-', $this['order']['start_date']);

        //$templateParams['startDate'] = $this['order']['start_date'] . '~' . $this['order']['end_date'];
        $templateParams['startDate'] = '按实际陪护开始及结束日期计';

        $templateParams['peihuTime'] = $this['order']['peihu_time'];

        $templateParams['day'] = $this['order']['day'];

        $templateParams['hour']     = 0;
        $templateParams['hourType'] = $this['order']['hour_type'] == 10 ? 12 : 24;
        $templateParams['dayFee']   = $this['order']['goods'][0]['goods_price']; //收费标准
        if ($this['order']['is_bed'] == 1) {
            $templateParams['bedFee'] = '陪床费5元/天。'; //陪床费
        } else {
            $templateParams['bedFee'] = '无'; //陪床费
        }

        $templateParams['serviceType'] = ['一对一陪护服务'];

        $date = Date('Y-m-d');

        $date = explode('-', $date);

        $templateParams['signYear']  = $date[0];
        $templateParams['signMonth'] = $date[1];
        $templateParams['signDay']   = $date[2];

        $goods_id = Db::name('order_goods')
            ->where('order_id', $this['order_id'])->value('goods_id');
        $contract_type = Db::name('goods')
            ->where('goods_id', $goods_id)->value('contract_type');
        $templateNo = Db::name('contract_type')->where('category_id', $contract_type)->value('template_id');

        $model                = new DriverModel;
        $data['orderNo']      = OrderService::createOrderNo();
        $data['idcard']       = $data['face_idcard'];
        $data['contractName'] = '佳佳陪护协议';
        $data['signatories']  = json_encode([$signatories, $signatoriesCompany]);
        //$data['orderFlag']       = 1;
        $data['serverCa']       = 1;
        $data['positionType']   = 2;
        $data['dealType']       = 5; //手签
        $data['fileType']       = 4; //pdf模版
        $data['templateNo']     = $templateNo;
        $data['templateParams'] = json_encode($templateParams);

        // $data['url'] = base_url() . $this['path'];

        if ($this['face_status'] == 0) {
            $result = $model->applySign($data);

            $contract_no  = '';
            $contract_url = '';
            if (isset($result['data'])) {
                $contract_no = $result['data'];
                $model       = new DriverModel;

                $dd['applyNo']         = $contract_no;
                $dd['fullName']        = $data['face_name'];
                $dd['identityCard']    = $data['face_idcard'];
                $dd['identityType']    = 1;
                $dd['useCustomDomain'] = 1;

                $rr = $model->getLink($dd);
                if (isset($rr['data'])) {
                    $contract_url = $rr['data'];
                }

            } else {
                $this->error = '页面已过期，请从新进入';
                return false;
            }
        } else {
            //继续签约

            $model                 = new DriverModel;
            $contract_no           = $this['contract_no'];
            $dd['applyNo']         = $contract_no;
            $dd['fullName']        = $data['face_name'];
            $dd['identityCard']    = $data['face_idcard'];
            $dd['identityType']    = 1;
            $dd['useCustomDomain'] = 1;

            $rr = $model->getLink($dd);
            if (isset($rr['data'])) {
                $contract_url = $rr['data'];
            }
        }

        $this->save([
            'age'         => $data['age'],
            'face_name'   => $data['face_name'],
            'face_mobile' => $data['face_mobile'],
            'idcard_date' => $data['idcard_date'],
            'idcard1'     => $data['idcard1'],
            'idcard2'     => $data['idcard2'],
            'order_no'    => $data['orderNo'],
            'contract_no' => $contract_no,
            'face_url'    => $contract_url, //签约地址
            'face_status' => 1,
            'face_idcard' => $data['face_idcard'],

        ]);

        return $rr;
    }
    //唤醒小程序人脸识别
    public function editUser2(array $data)
    {

        $userId = UserService::getCurrentLoginUserId();

        if ($this['face_idcard'] == '') {
            //更新个人证书
            $model              = new DriverModel;
            $dd['fullName']     = $data['face_name'];
            $dd['identityCard'] = $data['face_idcard'];
            $dd['idenFront']    = $data['idcard1_url'];
            $dd['idenReverse']  = $data['idcard2_url'];

            $ddResult = $model->cloudCertiPerInfo($dd);
            // print_r($ddResult);exit;
        }

        $model                = new DriverModel;
        $data['orderNo']      = OrderService::createOrderNo();
        $data['name']         = $data['face_name'];
        $data['identityCard'] = $data['face_idcard'];

        $result = $model->startMiniAppFace($data);

        $userData['face_name']   = $data['face_name'];
        $userData['face_mobile'] = $data['face_mobile'];
        $userData['face_idcard'] = $data['face_idcard'];
        $userData['idcard_date'] = $data['idcard_date'];
        $userData['idcard1']     = $data['idcard1'];
        $userData['idcard2']     = $data['idcard2'];

        Db::name('user')->where('user_id', $userId)->update($userData);

        $this->save([
            'age'           => $data['age'],
            'face_name'     => $data['face_name'],
            'face_mobile'   => $data['face_mobile'],
            'idcard_date'   => $data['idcard_date'],
            'idcard1'       => $data['idcard1'],
            'idcard2'       => $data['idcard2'],
            'order_no'      => $data['orderNo'],
            'face_order_no' => $result['data']['faceOrderNo'],
            'h5face_id'     => $result['data']['h5faceId'],
            'face_idcard'   => $data['face_idcard'],

        ]);

        return $result;
    }
    /**
     * 获取列表
     * @return \think\Paginator
     * @throws BaseException
     * @throws \think\db\exception\DbException
     */
    public function getList(): \think\Paginator
    {

        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 获取列表数据
        return $this->with(['order.goods'])
            ->where('user_id', '=', $userId)
            ->where('face_status', '>', 0)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    public function getContractStatus()
    {

        $model = new DriverModel;

        $data['applyNo']      = $this['contract_no'];
        $data['fullName']     = $this['face_name'];
        $data['identityCard'] = $this['face_idcard'];
        $data['identityType'] = 1;

        $result = $model->getContractStatus($data);

        if (isset($result['data'])) {
            if ($result['data'] == 2 || $result['data'] == 3) {
                //获取合同链接
                $ss       = new DriverModel;
                $response = $ss->getLinkFile($data);
                $url      = $response['data'];
                $path     = "pdf/" . $this['order_id'] . '-' . $this['real_name'] . ".pdf";
                $this->saveUrlToFile($url, $path);
                $this->save([
                    'path'         => $path,
                    'face_status'  => 2,
                    'contract_url' => $response['data'],

                ]);
            }
        }

        return $result;

    }

    public function getLinkFile()
    {

        $model = new DriverModel;

        $data['applyNo'] = $this['contract_no'];

        $result = $model->getLinkFile($data);

        if (isset($result['data'])) {
            $url  = $result['data'];
            $path =  "pdf/" . $this['order_id'] . '-' . $this['real_name'] . ".pdf";
            
            $this->saveUrlToFile($url, $path);
            $this->save([
                'path'         => $path,
                'face_status'  => 1,
                'contract_url' => $result['data'],

            ]);
        }

        return $result;

    }
    public function editUserH5(array $data): bool
    {

        $userId = UserService::getCurrentLoginUserId();

        $model                = new DriverModel;
        $data['orderNo']      = OrderService::createOrderNo();
        $data['name']         = $data['face_name'];
        $data['identityCard'] = $data['face_idcard'];

        //$data['backUrl'] = 'https://dshsc.zhanyuankj.cn/jiajia';

        $data['backUrl']         = 'https://dshsc.zhanyuankj.cn/jiajia/index.html#/pages/order/contract/check?pageId=10004?orderId=' . $this['order_id'];
        $data['startFrom']       = 1;
        $data['useCustomDomain'] = 1;

        $result = $model->getFaceUrl($data);

        $startFaceShortUrl = $result['data']['startFaceShortUrl'];

        $userData['face_name']   = $data['face_name'];
        $userData['face_mobile'] = $data['face_mobile'];
        $userData['face_idcard'] = $data['face_idcard'];

        Db::name('user')->where('user_id', $userId)->update($userData);

        // 更新收货地址
        return $this->save([
            'face_name'   => $data['face_name'],
            'face_mobile' => $data['face_mobile'],
            'order_no'    => $data['orderNo'],
            'face_url'    => $startFaceShortUrl,

            'face_idcard' => $data['face_idcard'],

        ]) !== false;
    }

}
